<?php

namespace App\Console\Commands;

use App\Library\Logic\AuctionLogic;
use App\Library\Logic\AuctionOrderLogic;
use App\Library\Service\WxMessageService;
use App\Models\AuctionBidModel;
use App\Models\OpenIdModel;
use Exception;
use Illuminate\Console\Command;

class AuctionEndCommand extends Command
{
    /**
     * 拍卖结束更改结束参数状态
     *
     * @var string
     */
    //protected $signature = 'command:auctionEnd {serialNumber}';
    protected $signature = 'command:auctionEnd';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Execute the console command.
     * @throws Exception
     */
    public function handle(): void
    {
        $list = AuctionLogic::query()->where(humpToLine([
            'status' => 1,
            'auditStatus' => 1,
            'isStart' => 1,
            'isEnd' => 0,
        ]))->where([
            ['end_at', '<=', now()->toDateTimeString()
            ]])->get();
        foreach ($list as $auction) {
            $auction->is_end = 1;
            if (is_null($auction->bid)) {//流拍
                $auction->expired = 1;
                $auction->save();
                mq('AuctionBailRefundAllCommand', $auction);
                continue;
            }
            $auction->bid->is_last = 1;
            if ($auction->bid->num === 1 && (float)$auction->start_price == 0) {//流拍
                $auction->expired = 1;
                $auction->save();
                mq('AuctionBailRefundAllCommand', $auction);
                continue;
            }
            $auction->sell_out = 1;
            $auctionOrder = AuctionOrderLogic::insertForModel([
                'auctionId' => $auction->id,
                'fileId' => $auction->file_id,
                'title' => $auction->title,
                'userId' => $auction->bid->user_id,
                'sellerId' => $auction->publish_id,
                'payPrice' => bcadd($auction->bid->price, $auction->freight, 2),
                'orderPrice' => $auction->bid->price,
                'freight' => $auction->freight,
                'payEndAt' => now()->parse($auction->end_at)->addDays(3),
                'createdAt' => $auction->end_at,
            ]);
            $auction->save();
            mq('auctionPayEnd', $auctionOrder, $auctionOrder->pay_end_at);
            mq('AuctionBailRefundAllCommand', $auction);
            $userInfo = OpenIdModel::query()->where([
                'user_id' => $auction->bid->user_id,
                'type' => 'wx'
            ])->first();
            WxMessageService::auctionWxMess($auctionOrder,$userInfo);
        }
    }
}
